package com.correo.vista.client.windows.ventanasInternas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Iterator;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;

import com.correo.database.beans.CasillaCorreoBean;
import com.correo.database.beans.MailBean;
import com.correo.database.beans.MailEnviadosBean;
import com.correo.database.beans.MensajeBean;
import com.correo.database.beans.UserBean;
import com.correo.modelo.client.ModelClient;
import com.correo.vista.client.windows.Correo;
import com.correo.vista.client.windows.componentes.menu.ItemMenuDinamicos;
import com.correo.vista.client.windows.event.ActionListenerIntFrameClose;
import com.correo.vista.client.windows.event.ActionListenerItemMenuDinamico;
import com.correo.vista.server.windows.AdministracionCorreo;


public class InternalFrameNuevoMensaje extends InternalFrameImpl{

	public static InternalFrameNuevoMensaje internal;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private ItemMenuDinamicos itemMenu;
	
	
	public static InternalFrameNuevoMensaje getInstance(){
		if(internal==null){
			internal = new InternalFrameNuevoMensaje();			
		}
		return internal;
	}
	public static InternalFrameNuevoMensaje getInstance(ModelClient modelClient){
		if(internal==null){
			internal = new InternalFrameNuevoMensaje();			
		}
		if(model==null){
			model = modelClient;
		}
		
		return internal;
	}
	public void inicializarVentana(Correo correo) throws ClassNotFoundException, SQLException{
		agregarItemCasillasCorreo(model.getCasillaCorreo(correo.getUserConnect()));
		this.correo  = correo;
	}
//	private void agregarItemCasillasCorreo(List<CasillaCorreoBean> casillaCorreo) {
//		if(casillaCorreo!=null){
//			Iterator<CasillaCorreoBean > it = casillaCorreo.iterator();
//			cboCasillasCorreo.setModel(getModelCombo());
//			while(it.hasNext()){
//				cboCasillasCorreo.addItem(it.next());
//			}
//		}
//	}
	private ComboBoxModel getModelCombo() {
		
		return new javax.swing.DefaultComboBoxModel(
				new String[] {});
	}
	private InternalFrameNuevoMensaje(){
		super("Nuevo Mensaje",true,true,true,true);
		createComponent();
		initComponent();
		
		//cboCasillasCorreo.removeAll();
	}
	
	
	public void inicializarNuevoMensaje(MailBean mail,String tipo){
		/*Cargar la "casilla de" que corresponde. 
		cbocasillascorreo*/
		
		cboCasillasCorreo.setSelectedItem(mail.getCasillaRecive().getId());
		
		if(tipo.equals("responder")){
			txtPara.setText(mail.getCasillaSend().getId().trim());
			txtAsunto.setText("Re:" + mail.getSubject().trim());
		}else{
			txtPara.setText("");
			txtAsunto.setText("Rv:" + mail.getSubject().trim());
		}
		
		System.out.println(mail.getSubject());
		jtpTextoMensaje.setText("Texto original" + mail.getMensaje().getContent() +
				"\n**************************");
	
		inicializarVentana();
		
		
	}
	
private void inicializarVentana() {
	
		
		if(!isVisible()){
				correo.getPanelPrincipal().add(this);
				setVisible(true);
				ItemMenuDinamicos item = new ItemMenuDinamicos(this,correo.getPanelPrincipal());
				setItemMenu(item);
				correo.addItemMenu(item);	
			
		}
		try {
			setSelected(true);
			setModelClient(correo.getModelClient());
			inicializarVentana(correo);
			correo.setTextStatus(InternalFrameConsultaRecibidos.getInstance().getTitle());
		} catch (PropertyVetoException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}					
		
		
	}
	

		

//	private void borrarCombo() {
//		
//		int cantidad = cboCasillasCorreo.getItemCount();
//		for(int i=0;i<cantidad;i++){
//			((DefaultComboBoxModel)cboCasillasCorreo.getModel()).removeElementAt(0);
//			//cboCasillasCorreo.remove(0);
//		}
//		
//	}

	private void createComponent(){
	     jToolBar1 = new javax.swing.JToolBar();
	        btnEnviar = new javax.swing.JButton();
	        btnSalir = new javax.swing.JButton();
	        jPanel1 = new javax.swing.JPanel();
	        jPanel2 = new javax.swing.JPanel();
	        lblCasillaCorreo = new javax.swing.JLabel();
	        cboCasillasCorreo = new javax.swing.JComboBox();
	        btnPara = new javax.swing.JButton();
	        txtPara = new javax.swing.JTextField();
	        lblAsunto = new javax.swing.JLabel();
	        txtAsunto = new javax.swing.JTextField();
	        jPanel3 = new javax.swing.JPanel();
	        jScrollPane1 = new javax.swing.JScrollPane();
	        jtpTextoMensaje = new javax.swing.JTextPane();
	        jSeparator2 = new javax.swing.JSeparator();
	        cboPrioridades = new javax.swing.JComboBox();
	}
	
	private void initComponent(){
			setActionListener();
			setName("Form"); // NOI18N

	        jToolBar1.setRollover(true);
	        jToolBar1.setName("jToolBar1"); // NOI18N

	        
	        btnEnviar.setText("Enviar"); // NOI18N
	        btnEnviar.setFocusable(false);
	        btnEnviar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
	        btnEnviar.setName("btnEnviar"); // NOI18N
	        btnEnviar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
	        jToolBar1.add(btnEnviar);

	        btnSalir.setText("Salir"); // NOI18N
	        btnSalir.setFocusable(false);
	        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
	        btnSalir.setName("btnSalir"); // NOI18N
	        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
	        jToolBar1.add(btnSalir);

	        jPanel1.setName("jPanel1"); // NOI18N

	        jPanel2.setName("jPanel2"); // NOI18N

	        lblCasillaCorreo.setText("Casilla:"); // NOI18N
	        lblCasillaCorreo.setName("lblCasillaCorreo"); // NOI18N

	        cboCasillasCorreo.setModel(getModelCombo());
	        cboCasillasCorreo.setName("cboCasillasCorreo"); // NOI18N

	        btnPara.setText("Para"); // NOI18N
	        btnPara.setName("btnPara"); // NOI18N
	        btnPara.addActionListener(new handlerbtnPara());
	        
	        txtPara.setText(""); // NOI18N
	        txtPara.setName("txtPara"); // NOI18N
	        txtPara.setEditable(false);

	        lblAsunto.setText("Asunto:"); // NOI18N
	        lblAsunto.setName("lblAsunto"); // NOI18N

	        txtAsunto.setName("txtAsunto"); // NOI18N

	        jSeparator2.setName("jSeparator2"); // NOI18N

	        cboPrioridades.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Normal", "Urgente", "Informativo"}));
	        cboPrioridades.setName("cboPrioridades"); // NOI18N

	        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
	        jPanel2.setLayout(jPanel2Layout);
	        jPanel2Layout.setHorizontalGroup(
	            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
	            .addGroup(jPanel2Layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(jPanel2Layout.createSequentialGroup()
	                        .addGap(19, 19, 19)
	                        .addComponent(lblCasillaCorreo)
	                        .addGap(28, 28, 28)
	                        .addComponent(cboCasillasCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
	                    .addGroup(jPanel2Layout.createSequentialGroup()
	                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addGroup(jPanel2Layout.createSequentialGroup()
	                                .addGap(10, 10, 10)
	                                .addComponent(lblAsunto))
	                            .addComponent(btnPara))
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addComponent(txtAsunto, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)
	                            .addComponent(txtPara, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)
	                            .addComponent(cboPrioridades, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))))
	                .addContainerGap(26, Short.MAX_VALUE))
	        );
	        jPanel2Layout.setVerticalGroup(
	            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel2Layout.createSequentialGroup()
	                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(lblCasillaCorreo)
	                    .addComponent(cboCasillasCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(btnPara)
	                    .addComponent(txtPara, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(lblAsunto)
	                    .addComponent(txtAsunto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(cboPrioridades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addContainerGap())
	        );

	        jPanel3.setName("jPanel3"); // NOI18N

	        jScrollPane1.setName("jScrollPane1"); // NOI18N

	        jtpTextoMensaje.setName("jTextPane1"); // NOI18N
	        jScrollPane1.setViewportView(jtpTextoMensaje);

	        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
	        jPanel3.setLayout(jPanel3Layout);
	        jPanel3Layout.setHorizontalGroup(
	            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
	        );
	        jPanel3Layout.setVerticalGroup(
	            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
	                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
	                .addContainerGap())
	        );

	        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
	        jPanel1.setLayout(jPanel1Layout);
	        jPanel1Layout.setHorizontalGroup(
	            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	        );
	        jPanel1Layout.setVerticalGroup(
	            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
	                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	        );

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
	            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );

	        pack();
    }// </editor-fold>
		
	public void agregarItemCasillasCorreo(java.util.List<CasillaCorreoBean> listaItems){
		if(listaItems!=null){
			Iterator<CasillaCorreoBean> it =listaItems.iterator();
			cboCasillasCorreo.setModel(getModelCombo());
			((DefaultComboBoxModel)cboCasillasCorreo.getModel()).removeAllElements();
			
			CasillaCorreoBean casilla;
			while(it.hasNext()){
				casilla = it.next();
				cboCasillasCorreo.addItem(casilla);
			}
		}
	}
	public ItemMenuDinamicos getItemMenu() {
		return itemMenu;
	}
	public void setItemMenu(ItemMenuDinamicos itemMenu) {
		this.itemMenu = itemMenu;
	}
	
	private boolean isValidEnviar(){
		boolean valid= true;
		String msj;
		
		if (cboCasillasCorreo.getSelectedIndex() == -1){
			msj= "Debe seleccionar una casilla de correo";
			valid= false;
		}else if (txtPara.getText().trim().length() == 0){
			msj= "Debe seleccionar un destinatario";
			valid= false;			
		}else{
			msj= "";
		}
	
						
		return valid;
	}
	private void setActionListener(){
		btnEnviar.addActionListener(new ActionListenerEnviar());
		btnSalir.addActionListener(new ActionListenerSalir());
	}
    // Variables declaration - do not modify
    private javax.swing.JButton btnEnviar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton btnPara;
    private javax.swing.JComboBox cboCasillasCorreo;
    private javax.swing.JComboBox cboPrioridades;
    private javax.swing.JLabel lblCasillaCorreo;
    private javax.swing.JLabel lblAsunto;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextField txtPara;
    private javax.swing.JTextField txtAsunto;
    private javax.swing.JTextPane jtpTextoMensaje;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JDialog dialogo;
    
    // End of variables declaration	
	
    
    class handlerbtnPara implements ActionListener {
    	public void actionPerformed( ActionEvent e ) {
    	//	new VentanaSeleccionarDestinatarios().setVisible(true);
    		if (dialogo== null) {
    			dialogo= new DialogoSeleccionarDestinatarios(internal);
    		}
    		try {
				((DialogoSeleccionarDestinatarios)dialogo).inicializarTabla();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    		dialogo.setVisible(true);
    	}
	}


	
    class ActionListenerEnviar implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			if(isValidEnviar()){
				//aca ejecuto el metodo del model que envia el mensaje o que es igual
				//escribe en la base el mensaje a su respectivo casila de correo
				//*seria algo asi
				//model.enviarNuevoMensaje(nuevoMensajeBean);
				System.out.println(" Se envio un nuevo mensaje");
				MailBean mail = new MailBean();
				MailEnviadosBean mailEnviado = new MailEnviadosBean();
				CasillaCorreoBean casillaSend = new CasillaCorreoBean();
				CasillaCorreoBean casillaRecive;
				MensajeBean mensaje = new MensajeBean();
				
				casillaSend.setId(((DefaultComboBoxModel)cboCasillasCorreo.getModel()).getSelectedItem().toString());
				mailEnviado.setCasillaEnvia(casillaSend);
				
				String[] veccasillas = txtPara.getText().split(";");
				for(int i=0;i<veccasillas.length;i++){
					casillaRecive = new CasillaCorreoBean();
					casillaRecive.setId(veccasillas[0]);
					mailEnviado.getListCasillaRecibe().add(casillaRecive);
				}
				mail.setMailEnviado(mailEnviado);
				mail.setState("No Leido");
				mail.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
				mail.setDateSend(new Timestamp(Calendar.getInstance().getTimeInMillis()));
				mail.setDateRecive(new Timestamp(Calendar.getInstance().getTimeInMillis()));
				mensaje.setImportance(((DefaultComboBoxModel)cboPrioridades.getModel()).getSelectedItem().toString());
				mensaje.setContent(jtpTextoMensaje.getText());
				mensaje.setImportance(((DefaultComboBoxModel)cboPrioridades.getModel()).getSelectedItem().toString());
				mensaje.setSubject(txtAsunto.getText());
				mail.setMensaje(mensaje);
				try {
					correo.getModelClient().enviarMail(mail);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
		}
    	
    }
    class ActionListenerSalir implements ActionListener{

		public void actionPerformed(ActionEvent e) {
//			try {
//				//setClosed(true);
//			} catch (PropertyVetoException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
		}
    	
    }
	public UserBean getUsuarioConectado() {
		// TODO Auto-generated method stub
		return correo.getUserConnect();
	}
	public CasillaCorreoBean getCasillaCorreo() {
		
		return (CasillaCorreoBean) ((DefaultComboBoxModel)cboCasillasCorreo.getModel()).getSelectedItem();
	}
    
}
